clear
% cd Y:\2011-04-double-crystal-bts\data-nearfield-profiles\
% filenames = ls('bt_m50_l75_g25_t30_xb*yb*xa*ya*nearfield_xy*txt');

% cd Y:\2011-04-01' - benson try 2'\data-nearfield-profiles\
% filenames = ls('*nearfield_xy.txt');

% cd Y:\2011-04-gap-12nm-double-crystal-bts\data-nearfield-profiles\
% filenames = ls('bt_m50_l75_g*_t30_xa*ya*xb*yb*nearfield_xy*txt');

% cd Y:\2011-04-gap-10nm-double-crystal-bts\data-nearfield-profiles
% filenames = ls('bt_m50_l75_g*_t30_xa*ya*xb*yb*nearfield_xy*txt');

filenames = ls('*nearfield_xy*.txt');

filenames=strtrim(mat2cell(filenames,ones(size(filenames,1),1),size(filenames,2)));
fspfiles = cell(size(filenames));
data=struct('filename',fspfiles,'field',fspfiles,'x',fspfiles,'y',fspfiles,'z',fspfiles,'lambda',fspfiles);
%%
for ii=1:length(filenames)
    prof = load(filenames{ii});
    f=fopen(filenames{ii});
    try
        textline = fgetl(f);
        tokens=regexp(textline,'lambda=([\d\.e\+]*).* ([^ .]*)','tokens');
        lambda=tokens{1}{1};
        fspfiles{ii}=tokens{1}{2};
        textline = fgetl(f);
        tokens=regexp(textline,'(\w)=(\d*\.?\d*)','tokens');
        idleaxisname=tokens{1}{1};
        idleaxis=tokens{1}{2};
        axisnames='xyz';
        workingaxes=upper(axisnames(axisnames~=idleaxisname));
    catch E
        disp(textline);
        fclose(f);
        throw(E);
    end
    fclose(f);
    data(ii) = struct('filename',filenames{ii},'field',prof(2:end,2:end),'x',prof(2:end,1),'y',prof(1,2:end),'z',str2double(idleaxis),'lambda',lambda);
end
[tmp, ind] = sort([data.z]);
data=data(ind);
clear filenames idleaxis idleaxisname ii axisnames f ind tmp prof textline tokens workingaxes lambda
fspfiles=unique(fspfiles);
%%
colors='rgbmk';
linetypes={'-','--',':','-.'};
if ~exist('linecuts','dir')
    system(['mkdir "' pwd '\linecuts"']);
end
maxval=-Inf;
for jj=1:length(fspfiles)
    figure(jj);
    clf;
    hold on;
    title(strrep(fspfiles{jj},'_','\_'));
    legstr={};
    col=1;
    xlabel('X/nm');
    ylabel('|E|');
    
    for ii=1:length(data)
        if strfind(data(ii).filename,[fspfiles{jj} '_nearfield'])==1
            linecut=data(ii).field(:,abs(data(ii).y)==min(abs(data(ii).y)));
            
            maxval=max([maxval; linecut]);
            col=col+1;
            linetype=ceil((col-1)/length(colors));
            plot(data(ii).x,linecut,[colors(mod(col,length(colors))+1) linetypes{linetype}]);

            legstr{end+1}=['z=' num2str(data(ii).z) 'nm'];
        end
    end
    xlim([0 30]);
%     ylim([0 1.05]*maxval);
    legend(legstr);
    hold off
%     print('-dpng',['.\linecuts\' fspfiles{jj} '_linecuts']);
end

for jj=1:length(fspfiles)
    figure(jj);
    ylim([0 1.05]*maxval);
    print('-dpng',['.\linecuts\' fspfiles{jj} '_linecuts']);
end

% close all